<?php
/**
 * Typecho云盘第三方文件上传插件
 * 集成API接口实现文件上传功能
 * 
 * @package TypechoCloudUpload
 * @author 小渡API
 * @version 1.2.1
 * @link https://api.dwo.cc
 * 
 * Copyright [年份] [小渡API]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
class TypechoCloudUpload_Plugin implements Typecho_Plugin_Interface
{
    public static function activate()
    {
        // 插件激活逻辑
        // 文件完整性检查已移至showCopyrightNotice方法中
        
        Typecho_Plugin::factory('Widget_Upload')->uploadHandle = array('TypechoCloudUpload_Plugin', 'uploadToCloud');
        Typecho_Plugin::factory('Widget_Upload')->modifyHandle = array('TypechoCloudUpload_Plugin', 'modifyToCloud');
        Typecho_Plugin::factory('Widget_Upload')->attachmentHandle = array('TypechoCloudUpload_Plugin', 'customAttachmentHandle');

        Typecho_Plugin::factory('admin/write-post.php')->bottom = array('TypechoCloudUpload_Plugin', 'render');
        Typecho_Plugin::factory('admin/write-page.php')->bottom = array('TypechoCloudUpload_Plugin', 'render');
        
        self::addCopyrightNotice();
        
        return '插件激活成功，请在设置中配置API信息';
    }
    
    private static function addCopyrightNotice()
    {
        Typecho_Plugin::factory('admin/footer.php')->end = array('TypechoCloudUpload_Plugin', 'showCopyrightNotice');
    }
    
    public static function showCopyrightNotice()
    {
        $copyrightInfo = "速纳云盘上传插件\n\n版本：1.2.1\n作者：小渡API\n官网：https://api.dwo.cc\n注册获取AID和KEY：https://snpan.com?a=34\n\n注意：本插件完全免费使用！\n请勿用于任何商业用途的非法传播。\n\n感谢您的支持！\n\n本插件采用Apache许可证2.0发布。";
        
        $expectedSignature = '3CA6AE66031B885302F2B3B661F4D68C';
        
        $actualSignature = md5($copyrightInfo);
        
        if ($actualSignature !== $expectedSignature) {
            $message = "警告：插件文件可能已被修改！\n\n为了保护您的网站安全，请从官方渠道重新下载插件。\n\n官方网址：https://api.dwo.cc\n注册获取AID和KEY：https://snpan.com?a=34";
        } else {
            $message = $copyrightInfo;
        }
        
        echo '<script>
        document.addEventListener("DOMContentLoaded", function() {
            // Create a more visible notice element
            var noticeDiv = document.createElement("div");
            noticeDiv.innerHTML = "' . str_replace("\n", "<br>", $message) . '";
            noticeDiv.style.cssText = "position:fixed;top:20px;right:20px;padding:15px;background:#fff;border:1px solid #ccc;box-shadow:0 2px 10px rgba(0,0,0,0.1);z-index:10000;border-radius:5px;font-size:14px;max-width:300px;";
            
            // Add a close button
            var closeBtn = document.createElement("button");
            closeBtn.innerHTML = "×";
            closeBtn.style.cssText = "position:absolute;top:5px;right:5px;background:none;border:none;font-size:18px;font-weight:bold;cursor:pointer;";
            closeBtn.onclick = function() { document.body.removeChild(noticeDiv); };
            noticeDiv.appendChild(closeBtn);
            
            // Show the notice
            if (!localStorage.getItem("snpan_copyright_shown")) {
                document.body.appendChild(noticeDiv);
                localStorage.setItem("snpan_copyright_shown", "true");
                
                // Auto-hide after 10 seconds
                setTimeout(function() { 
                    if (document.body.contains(noticeDiv)) {
                        document.body.removeChild(noticeDiv);
                    }
                }, 10000);
            }
        });
        </script>';
    }
    
    public static function deactivate() {}
    
    public static function config(Typecho_Widget_Helper_Form $form)
    {
        $aid = new Typecho_Widget_Helper_Form_Element_Text(
            'aid', 
            NULL, 
            '', 
            _t('API AID'), 
            _t('请输入您的API访问AID')
        );
        $form->addInput($aid);
        
        $key = new Typecho_Widget_Helper_Form_Element_Text(
            'key', 
            NULL, 
            '', 
            _t('API KEY'), 
            _t('请输入您的API访问KEY')
        );
        $form->addInput($key);
        
        // 添加注册链接说明
        $registrationNote = new Typecho_Widget_Helper_Form_Element_Textarea(
            'registrationNote', 
            NULL, 
            '', 
            _t('<a href="https://snpan.com?a=34" target="_blank">注册获取AID和KEY</a>'), 
            _t('点击上方链接注册账号并获取AID和KEY')
        );
        $registrationNote->input->setAttribute('readonly', 'readonly');
        $registrationNote->input->setAttribute('style', 'border: none; background: none; padding: 0;');
        $form->addInput($registrationNote);
        
        $fid = new Typecho_Widget_Helper_Form_Element_Text(
            'fid', 
            NULL, 
            '', 
            _t('默认文件夹ID'), 
            _t('可选，留空则上传到根目录')
        );
        $form->addInput($fid);
        
        $apiUrl = new Typecho_Widget_Helper_Form_Element_Text(
            'apiUrl', 
            NULL, 
            'https://api.snpan.com/opapi', 
            _t('API基础地址'), 
            _t('API服务的基础地址，一般无需修改')
        );
        $form->addInput($apiUrl);
    }
    
    public static function personalConfig(Typecho_Widget_Helper_Form $form) {
    }
    
    public static function uploadToCloud($file)
    {
        $options = Typecho_Widget::widget('Widget_Options')->plugin('TypechoCloudUpload');
        $aid = $options->aid;
        $key = $options->key;
        $fid = $options->fid;
        $apiUrl = $options->apiUrl;
        
        if (empty($aid) || empty($key)) {
            return false;
        }
        
        try {
            $authResponse = self::sendRequest($apiUrl . "/GetAuthCode?aid=" . urlencode($aid) . "&key=" . urlencode($key));
            $authData = json_decode($authResponse, true);
            
            if ($authData['code'] !== 200) {
                return false;
            }
            
            $authCode = $authData['data'];
            
            $uploadUrlEndpoint = $apiUrl . "/Getuploads?authcode=" . urlencode($authCode);
            if (!empty($fid)) {
                $uploadUrlEndpoint .= "&fid=" . urlencode($fid);
            }
            
            $uploadUrlResponse = self::sendRequest($uploadUrlEndpoint);
            $uploadUrlData = json_decode($uploadUrlResponse, true);
            
            if ($uploadUrlData['code'] !== 200) {
                return false;
            }
            
            $uploadUrl = $uploadUrlData['data']['url'];
            $uploadQuery = $uploadUrlData['data']['query'];
            
            $uploadFullUrl = $uploadUrl . "/upload?" . $uploadQuery;
            
            $fileData = '';
            if (isset($file['tmp_name'])) {
                $fileData = file_get_contents($file['tmp_name']);
            } elseif (isset($file['bytes'])) {
                $fileData = $file['bytes'];
            } elseif (isset($file['bits'])) {
                $fileData = $file['bits'];
            } else {
                return false;
            }
            
            $uploadResponse = self::sendFileRequest($uploadFullUrl, $fileData, $file['name']);
            $uploadResult = json_decode($uploadResponse, true);
            
            if ($uploadResult['code'] !== 200) {
                return false;
            }
            
            $fileUrl = $uploadResult['data']['url'] ?? $uploadResult['data'];

            return [
                'name' => $file['name'],
                'path' => $fileUrl,
                'size' => $file['size'],
                'type' => self::getSafeName($file['name']),
                'mime' => $file['type'] ?? 'application/octet-stream',
                'isRemote' => true
            ];
        } catch (Exception $e) {
            return false;
        }
    }
    
    public static function modifyToCloud($content, $file)
    {
        return self::uploadToCloud($file);
    }
    
    public static function customAttachmentHandle($content)
    {
        return $content['attachment']->path;
    }
    
    private static function sendRequest($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return $response;
    }
    
    private static function sendFileRequest($url, $fileData, $fileName)
    {
        $ch = curl_init();
        
        $tempFile = tempnam(sys_get_temp_dir(), 'upload');
        file_put_contents($tempFile, $fileData);
        
        $postFields = [
            'file' => new CURLFile($tempFile, '', $fileName)
        ];
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        
        $response = curl_exec($ch);
        
        unlink($tempFile);
        
        curl_close($ch);
        
        return $response;
    }
    
    private static function getSafeName(string &$name): string
    {
        $name = str_replace(['"', '<', '>'], '', $name);
        $name = str_replace('\\', '/', $name);
        $name = false === strpos($name, '/') ? ('a' . $name) : str_replace('/', '/a', $name);
        $info = pathinfo($name);
        $name = substr($info['basename'], 1);

        return isset($info['extension']) ? strtolower($info['extension']) : '';
    }
    
    public static function render()
    {
        $options = Typecho_Widget::widget('Widget_Options')->plugin('TypechoCloudUpload');
        $aid = $options->aid;
        $key = $options->key;
        $fid = $options->fid;
        $apiUrl = $options->apiUrl;
        
        echo '<div class="file-upload-plugin" style="position: fixed; right: 20px; top: 100px; z-index: 1000;">';
        echo '<button id="fileUploadBtn" class="btn btn-s primary">';
        echo '<i class="i-upload"></i> 速纳云盘文件上传';
        echo '</button>';
        
        echo '<div id="fileUploadModal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:10000;">';
        echo '<div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:white;padding:20px;border-radius:8px;width:550px;max-width:90%;max-height:90%;overflow-y:auto;">';
        echo '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;border-bottom:1px solid #eee;padding-bottom:10px;">';
        echo '<h3 style="margin:0;">文件上传</h3>';
        echo '<button id="closeUploadModal" class="btn btn-s">关闭</button>';
        echo '</div>';
        
        echo '<div id="uploadSteps" style="margin-bottom:20px;">';
        echo '<div style="display:flex;position:relative;">';
        echo '<div style="position:absolute;top:10px;left:0;right:0;height:2px;background:#eee;z-index:1;"></div>';
        echo '<div id="progressLine" style="position:absolute;top:10px;left:0;height:2px;background:#4CAF50;z-index:2;width:0%;transition:width 0.3s;"></div>';
        
        echo '<div class="step" style="position:relative;z-index:3;text-align:center;width:33.333%;">';
        echo '<div id="step1Icon" style="width:22px;height:22px;border-radius:50%;background:#eee;color:white;margin:0 auto;line-height:22px;">1</div>';
        echo '<div style="margin-top:5px;font-size:12px;">验证授权</div>';
        echo '</div>';
        
        echo '<div class="step" style="position:relative;z-index:3;text-align:center;width:33.333%;">';
        echo '<div id="step2Icon" style="width:22px;height:22px;border-radius:50%;background:#eee;color:white;margin:0 auto;line-height:22px;">2</div>';
        echo '<div style="margin-top:5px;font-size:12px;">获取地址</div>';
        echo '</div>';
        
        echo '<div class="step" style="position:relative;z-index:3;text-align:center;width:33.333%;">';
        echo '<div id="step3Icon" style="width:22px;height:22px;border-radius:50%;background:#eee;color:white;margin:0 auto;line-height:22px;">3</div>';
        echo '<div style="margin-top:5px;font-size:12px;">上传文件</div>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        
        echo '<div class="section" id="section1">';
        echo '<h4 style="margin-top:0;">1. 验证授权信息</h4>';
        echo '<div id="authStatus" class="status" style="padding:10px;border-radius:4px;margin-bottom:10px;"></div>';
        echo '<button id="verifyAuthBtn" class="btn primary">验证授权</button>';
        echo '</div>';
        
        echo '<div class="section" id="section2" style="display:none;">';
        echo '<h4 style="margin-top:0;">2. 获取上传地址</h4>';
        echo '<label for="uploadFid">文件夹ID (可选):</label>';
        echo '<input type="text" id="uploadFid" value="' . htmlspecialchars($fid) . '" placeholder="输入文件夹ID，留空为根目录" style="width:100%;padding:8px;margin:10px 0;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;">';
        echo '<div id="uploadUrlStatus" class="status" style="padding:10px;border-radius:4px;margin-bottom:10px;"></div>';
        echo '<button id="getUploadUrlBtn" class="btn primary">获取上传地址</button>';
        echo '</div>';
        
        echo '<div class="section" id="section3" style="display:none;">';
        echo '<h4 style="margin-top:0;">3. 上传文件</h4>';
        echo '<label for="fileToUpload">选择文件:</label>';
        echo '<input type="file" id="fileToUpload" style="margin:10px 0;">';
        echo '<button id="startUploadBtn" class="btn primary" disabled>开始上传</button>';
        
        echo '<div style="width:100%;background-color:#f1f1f1;border-radius:4px;margin-top:10px;">';
        echo '<div id="progressBar" style="height:20px;border-radius:4px;background-color:#4CAF50;width:0%;transition:width 0.3s;text-align:center;color:white;line-height:20px;">0%</div>';
        echo '</div>';
        
        echo '<div id="uploadStatus" class="status" style="padding:10px;border-radius:4px;margin-top:10px;"></div>';
        echo '<div id="uploadResult" style="margin-top:10px;padding:10px;background-color:#f5f5f5;border-radius:4px;display:none;word-break:break-all;font-size:12px;"></div>';
        echo '</div>';
        
        echo '</div>';
        echo '</div>';
        echo '</div>';
        
        echo '<script>';
        echo 'document.addEventListener("DOMContentLoaded", function() {';
        echo '    const fileUploadBtn = document.getElementById("fileUploadBtn");';
        echo '    const fileUploadModal = document.getElementById("fileUploadModal");';
        echo '    const closeUploadModal = document.getElementById("closeUploadModal");';
        echo '    const verifyAuthBtn = document.getElementById("verifyAuthBtn");';
        echo '    const getUploadUrlBtn = document.getElementById("getUploadUrlBtn");';
        echo '    const startUploadBtn = document.getElementById("startUploadBtn");';
        echo '    const fileToUpload = document.getElementById("fileToUpload");';
        echo '    const progressBar = document.getElementById("progressBar");';
        echo '    const authStatus = document.getElementById("authStatus");';
        echo '    const uploadUrlStatus = document.getElementById("uploadUrlStatus");';
        echo '    const uploadStatus = document.getElementById("uploadStatus");';
        echo '    const uploadResult = document.getElementById("uploadResult");';
        echo '    const uploadFid = document.getElementById("uploadFid");';
        echo '    const progressLine = document.getElementById("progressLine");';
        echo '    const step1Icon = document.getElementById("step1Icon");';
        echo '    const step2Icon = document.getElementById("step2Icon");';
        echo '    const step3Icon = document.getElementById("step3Icon");';
        echo '    const section1 = document.getElementById("section1");';
        echo '    const section2 = document.getElementById("section2");';
        echo '    const section3 = document.getElementById("section3");';
        
        echo '    let authCode = "";';
        echo '    let uploadUrl = "";';
        echo '    let uploadQuery = "";';
        echo '    const aid = "' . htmlspecialchars($aid) . '";';
        echo '    const key = "' . htmlspecialchars($key) . '";';
        echo '    const apiBaseUrl = "' . htmlspecialchars($apiUrl) . '";';
        
        echo '    fileUploadBtn.addEventListener("click", function() {';
        echo '        fileUploadModal.style.display = "block";';
        echo '        resetUploadState();';
        echo '    });';
        
        echo '    closeUploadModal.addEventListener("click", function() {';
        echo '        fileUploadModal.style.display = "none";';
        echo '    });';
        
        echo '    window.addEventListener("click", function(event) {';
        echo '        if (event.target === fileUploadModal) {';
        echo '            fileUploadModal.style.display = "none";';
        echo '        }';
        echo '    });';
        
        echo '    fileToUpload.addEventListener("change", function() {';
        echo '        startUploadBtn.disabled = !this.files.length;';
        echo '    });';
        
        echo '    verifyAuthBtn.addEventListener("click", function() {';
        echo '        if (!aid || !key) {';
        echo '            showStatus(authStatus, "请先在插件设置中配置AID和KEY", "error");';
        echo '            return;';
        echo '        }';
        
        echo '        try {';
        echo '            showStatus(authStatus, "正在验证授权信息...", "loading");';
        echo '            verifyAuthBtn.disabled = true;';
        
        echo '            fetch(apiBaseUrl + "/GetAuthCode?aid=" + encodeURIComponent(aid) + "&key=" + encodeURIComponent(key))';
        echo '                .then(response => {';
        echo '                    if (!response.ok) {';
        echo '                        throw new Error("HTTP错误: " + response.status);';
        echo '                    }';
        echo '                    return response.json();';
        echo '                })';
        echo '                .then(data => {';
        echo '                    if (data.code !== 200) {';
        echo '                        throw new Error(data.msg || "验证授权失败");';
        echo '                    }';
        
        echo '                    authCode = data.data;';
        echo '                    showStatus(authStatus, "授权验证成功", "success");';
        echo '                    console.log("AuthCode获取成功:", authCode);';
        
        echo '                    step1Icon.style.background = "#4CAF50";';
        echo '                    progressLine.style.width = "33.333%";';
        echo '                    setTimeout(function() {';
        echo '                        section1.style.display = "none";';
        echo '                        section2.style.display = "block";';
        echo '                    }, 500);';
        
        echo '                })';
        echo '                .catch(error => {';
        echo '                    showStatus(authStatus, "验证失败: " + error.message, "error");';
        echo '                    verifyAuthBtn.disabled = false;';
        echo '                });';
        echo '        } catch (error) {';
        echo '            showStatus(authStatus, "验证失败: " + error.message, "error");';
        echo '            verifyAuthBtn.disabled = false;';
        echo '        }';
        echo '    });';
        
        echo '    getUploadUrlBtn.addEventListener("click", function() {';
        echo '        const fid = uploadFid.value.trim();';
        
        echo '        try {';
        echo '            showStatus(uploadUrlStatus, "正在获取上传地址...", "loading");';
        echo '            getUploadUrlBtn.disabled = true;';
        
        echo '            let url = apiBaseUrl + "/Getuploads?authcode=" + encodeURIComponent(authCode);';
        echo '            if (fid) {';
        echo '                url += "&fid=" + encodeURIComponent(fid);';
        echo '            }';
        
        echo '            fetch(url)';
        echo '                .then(response => {';
        echo '                    if (!response.ok) {';
        echo '                        throw new Error("HTTP错误: " + response.status);';
        echo '                    }';
        echo '                    return response.json();';
        echo '                })';
        echo '                .then(data => {';
        echo '                    if (data.code !== 200) {';
        echo '                        throw new Error(data.msg || "获取上传地址失败");';
        echo '                    }';
        
        echo '                    uploadUrl = data.data.url;';
        echo '                    uploadQuery = data.data.query;';
        echo '                    showStatus(uploadUrlStatus, "上传地址获取成功", "success");';
        echo '                    console.log("上传地址:", uploadUrl);';
        echo '                    console.log("查询参数:", uploadQuery);';
        
        echo '                    step2Icon.style.background = "#4CAF50";';
        echo '                    progressLine.style.width = "66.666%";';
        echo '                    setTimeout(function() {';
        echo '                        section2.style.display = "none";';
        echo '                        section3.style.display = "block";';
        echo '                    }, 500);';
        
        echo '                })';
        echo '                .catch(error => {';
        echo '                    showStatus(uploadUrlStatus, "获取失败: " + error.message, "error");';
        echo '                    getUploadUrlBtn.disabled = false;';
        echo '                });';
        echo '        } catch (error) {';
        echo '            showStatus(uploadUrlStatus, "获取失败: " + error.message, "error");';
        echo '            getUploadUrlBtn.disabled = false;';
        echo '        }';
        echo '    });';
        
        echo '    startUploadBtn.addEventListener("click", function() {';
        echo '        const file = fileToUpload.files[0];';
        echo '        if (!file) {';
        echo '            showStatus(uploadStatus, "请选择要上传的文件", "error");';
        echo '            return;';
        echo '        }';
        echo '        if (!uploadUrl || !uploadQuery) {';
        echo '            showStatus(uploadStatus, "请先获取上传地址", "error");';
        echo '            return;';
        echo '        }';

        echo '        try {';
        echo '            showStatus(uploadStatus, "正在上传文件...", "loading");';
        echo '            startUploadBtn.disabled = true;';
        echo '            progressBar.style.width = "0%";';
        echo '            progressBar.textContent = "0%";';
        echo '            uploadResult.style.display = "none";';

        echo '            const formData = new FormData();';
        echo '            formData.append("file", file);';
        echo '            const uploadFullUrl = uploadUrl + "/upload?" + uploadQuery;';
        echo '            console.log("完整上传地址:", uploadFullUrl);';

        echo '            const xhr = new XMLHttpRequest();';
        echo '            xhr.open("POST", uploadFullUrl, true);';
        
        echo '            xhr.upload.onprogress = function(event) {';
        echo '                if (event.lengthComputable) {';
        echo '                    const percent = Math.round((event.loaded / event.total) * 100);';
        echo '                    progressBar.style.width = percent + "%";';
        echo '                    progressBar.textContent = percent + "%";';
        echo '                }';
        echo '            };';
        
        echo '            xhr.onload = function() {
                if (xhr.status === 200) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        uploadResult.textContent = "服务器响应: " + xhr.responseText;
                        uploadResult.style.display = "block";
                    
                        if (response.code === 200 && response.data) {
                            showStatus(uploadStatus, "文件上传成功!", "success");
                            step3Icon.style.background = "#4CAF50";
                            progressLine.style.width = "100%";
                            let fileUrl = "";
                            if (typeof response.data === "string") {
                                fileUrl = response.data.trim();
                            } else if (response.data.url) {
                                fileUrl = response.data.url.trim();
                            } else {
                                fileUrl = response.data;
                            }
                            if (fileUrl.startsWith("`")) fileUrl = fileUrl.substring(1);
                            if (fileUrl.endsWith("`")) fileUrl = fileUrl.substring(0, fileUrl.length - 1);
                            insertToEditor(fileUrl, file.name);
                        } else {
                            showStatus(uploadStatus, "上传失败: " + (response.msg || "未知错误"), "error");
                        }
                    } catch (e) {
                        showStatus(uploadStatus, "解析响应失败", "error");
                        console.log("解析响应失败:", e);
                    }
                } else {
                    showStatus(uploadStatus, "上传失败: " + xhr.status + " - " + xhr.statusText, "error");
                }
                startUploadBtn.disabled = false;
            };';
        
        echo '            xhr.onerror = function() {';
        echo '                showStatus(uploadStatus, "网络错误，上传请求失败", "error");';
        echo '                startUploadBtn.disabled = false;';
        echo '            };';
        
        echo '            xhr.send(formData);';
        echo '        } catch (error) {';
        echo '            showStatus(uploadStatus, "上传失败: " + error.message, "error");';
        echo '            startUploadBtn.disabled = false;';
        echo '        }';
        echo '    });';
        
        echo '    function showStatus(element, message, type) {';
        echo '        element.textContent = message;';
        echo '        if (type === "error") {';
        echo '            element.style.color = "#d32f2f";';
        echo '            element.style.backgroundColor = "#ffebee";';
        echo '        } else if (type === "success") {';
        echo '            element.style.color = "#388e3c";';
        echo '            element.style.backgroundColor = "#e8f5e9";';
        echo '        } else if (type === "loading") {';
        echo '            element.style.color = "#666";';
        echo '            element.style.backgroundColor = "#f0f0f0";';
        echo '        }';
        echo '    }';
        
        echo '    function resetUploadState() {';
        echo '        authCode = "";';
        echo '        uploadUrl = "";';
        echo '        uploadQuery = "";';
        echo '        fileToUpload.value = "";';
        echo '        progressBar.style.width = "0%";';
        echo '        progressBar.textContent = "0%";';
        echo '        uploadResult.style.display = "none";';
        echo '        verifyAuthBtn.disabled = false;';
        echo '        getUploadUrlBtn.disabled = false;';
        echo '        startUploadBtn.disabled = true;';
        echo '        showStatus(authStatus, "", "");';
        echo '        showStatus(uploadUrlStatus, "", "");';
        echo '        showStatus(uploadStatus, "", "");';
        echo '        step1Icon.style.background = "#eee";';
        echo '        step2Icon.style.background = "#eee";';
        echo '        step3Icon.style.background = "#eee";';
        echo '        progressLine.style.width = "0%";';
        echo '        section1.style.display = "block";';
        echo '        section2.style.display = "none";';
        echo '        section3.style.display = "none";';
        echo '    }';
        
        echo '    function insertToEditor(url, fileName) {';
        echo '        let displayUrl = url;';
        echo '        if (displayUrl.startsWith("`")) displayUrl = displayUrl.substring(1);';
        echo '        if (displayUrl.endsWith("`")) displayUrl = displayUrl.substring(0, displayUrl.length - 1);';
        
        echo '        if (typeof editor !== "undefined" && editor.insert) {';
        echo '            const imageExts = /\.(jpg|jpeg|png|gif|bmp|webp)$/i;';
        echo '            const videoExts = /\.(mp4|webm|ogg|mov)$/i;';
        echo '            const audioExts = /\.(mp3|wav|ogg|flac)$/i;';
        echo '            const archiveExts = /\.(zip|rar|7z|tar|gz)$/i;';
        echo '            const docExts = /\.(pdf|doc|docx|xls|xlsx|ppt|pptx)$/i;';
        
        echo '            if (imageExts.test(displayUrl)) {';
        echo '                editor.insert("![" + fileName + "](" + displayUrl + ")");';
        echo '            } else if (videoExts.test(displayUrl)) {';
        echo '                editor.insert("<video src=\"" + displayUrl + "\" controls style=\"max-width:100%;\"></video>");';
        echo '            } else if (audioExts.test(displayUrl)) {';
        echo '                editor.insert("<audio src=\"" + displayUrl + "\" controls></audio>");';
        echo '            } else if (archiveExts.test(displayUrl) || docExts.test(displayUrl)) {';
        echo '                editor.insert("[" + fileName + "](" + displayUrl + ")");';
        echo '            } else {';
        echo '                editor.insert(displayUrl);';
        echo '            }';
        echo '            showStatus(uploadStatus, "文件上传成功，并已插入到编辑器", "success");';
        echo '        } else {';
        echo '            navigator.clipboard.writeText(displayUrl).then(function() {';
        echo '                showStatus(uploadStatus, "文件上传成功，链接已复制到剪贴板: " + displayUrl, "success");';
        echo '            }, function() {';
        echo '                showStatus(uploadStatus, "文件上传成功，链接: " + displayUrl, "success");';
        echo '            });';
        echo '        }';
        echo '    }';
        echo '});';
        echo '</script>';
    }
}